package com.haiheng.module_main.mode

import android.app.Application
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.haiheng.common.api.API
import com.haiheng.common.bean.UserInfoBean
import com.haiheng.common.bean.UserReqeBean
import com.haiheng.library.log.LogUtils
import com.haiheng.library.log.LogWriter
import com.haiheng.library_base.http.Domain
import com.haiheng.library_base.http.HttpRequest
import com.haiheng.library_base.http.postJson
import com.haiheng.library_base.model.BaseViewModel
import com.haiheng.library_base.msg.MsgCode
import kotlinx.coroutines.launch

/**
 *
 * @Des:
 * @Author: hwz
 * @Date:2022/4/25 0025
 * @Version: 1.0
 */
class LoginViewModel() : BaseViewModel() {
    private val _userInfoBean = MutableLiveData<UserInfoBean>()
    val userInfo: LiveData<UserInfoBean> = _userInfoBean

    var failCode = MutableLiveData<Int>()
    var failMsg = MutableLiveData<String>()




    /**
     * 根据读者证编号查询读者
     */
    fun queryPatronInfoByPatronSn(pntronSn:String,password:String){
        viewModelScope.launch {
            val request = HttpRequest(API.POST_PATH)
                .putHeader(Domain.KEY_NAME, Domain.VALUE_ACS)
                .setJsonObjec(RequestDataHelper.getLoginReqDataByPatronsnAndPassword(pntronSn,password))
            var response = postJson<UserReqeBean>(request)
            if (response.result != null && response.errorCode.equals("0")){
                LogWriter.e("登录成功${response.toJson()}")
                _userInfoBean.postValue(response.result!!)
            }else{
                LogWriter.e("登录失败${response}")
                failCode.postValue(MsgCode.MSG_LOGIN_FAIL_BY_PATRON)
                failMsg.postValue("code：${response.errorCode}  msg:${response.errorMsg} ${response.message}")
            }
            LogUtils.e("请求结果：${response.toJson()}")
        }
    }




    fun getUserInfoBean():UserInfoBean{
        var userInfo = _userInfoBean.value
        return _userInfoBean.value?:UserInfoBean()
    }

}